package com.wzt.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wzt.gift.asserts.Assert;
import com.wzt.gift.clients.UserClient;
import com.wzt.gift.domain.LoginUser;
import com.wzt.gift.domain.Permission;
import com.wzt.gift.dto.LoginUserDto;
import com.wzt.gift.enums.ResponseEnum;
import com.wzt.gift.mapper.LoginUserMapper;
import com.wzt.gift.mapper.PermissionMapper;
import com.wzt.gift.properties.OauthClientDetails;
import com.wzt.gift.properties.OauthClientDetailsProperties;
import com.wzt.gift.service.ILoginUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wzt.gift.util.AjaxResult;
import com.wzt.gift.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wzt
 * @since 2022-10-10
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {
    @Autowired
    private OauthClientDetailsProperties properties;
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private LoginUserMapper loginUserMapper;
    @Override
    public AjaxResult loginByAccount(LoginUserDto loginUserDto) {
        // 接收前端传过来的登录用户dto
        String username = loginUserDto.getUsername();
        String password = loginUserDto.getPassword();
        Integer type = loginUserDto.getType();

        // 获取boostrap.yml配置中的OauthClient信息
        OauthClientDetails oauthClientDetails = properties.getOauthClientDetails(type);
        String clientId = oauthClientDetails.getId();
        String clientSecret = oauthClientDetails.getSecret();

        // 获取令牌的地址，要通过网关
        String url = "http://localhost:10030/services/auth/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&password=%s";
        url = String.format(url, clientId, clientSecret, username, password);

        // 获取令牌的结果集合
        Map<String, String> httpResult = HttpUtil.sendPost(url);
        // 拿到结果中的令牌和刷新令牌
        String token = httpResult.get("access_token");
        String refreshToken = httpResult.get("refresh_token");

        // 定义登录请求返回结果集
        HashMap<String, Object> result = new HashMap<>();
        // 存放刚才获取到的令牌和刷新令牌
        result.put("token", token);
        result.put("refreshToken", refreshToken);

        // 获取登录用户基本信息
        EntityWrapper<LoginUser> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username)
                .or()
                .eq("email", username)
                .or()
                .eq("tel", username)
                .andNew()
                .eq("type", type);
        List<LoginUser> loginUsers = loginUserMapper.selectList(wrapper);
        Assert.listIsNotEmpty(loginUsers, ResponseEnum.CODE_USER_NOT_EXIST);
        // 存放登录用户
        result.put("loginUser", loginUsers.get(0));

        // 获取登录用户权限
        List<String> permissionSns = new ArrayList<>();
        if (type == 0) {
            List<Permission> permissions =
                    permissionMapper.selectPermissionsByUserId(loginUsers.get(0).getId());
                permissionSns = permissions.stream().map(permission -> permission.getSn()).collect(Collectors.toList());
        }
        // 存放权限
        result.put("permissions", permissionSns);

        return AjaxResult.me().setMessage("登录成功！").setResultObj(result);
    }
}